/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable */

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Row, Col, Tooltip, Spin } from 'antd';
import omit from 'omit.js';
import styles from './index.less';
import map from './map';
import { crypto } from '@/utils/encryption';
import { debounce } from 'lodash';
import qs from 'qs';
import { check } from '@/utils/patterns';

const FormItem = Form.Item;

function generator({ defaultProps, defaultRules, type }) {
  return WrappedComponent => {
    return class BasicComponent extends Component {
      static contextTypes = {
        form: PropTypes.object,
        updateActive: PropTypes.func,
      };

      static defaultProps = {
        buttonText: '获取验证码',
      };

      constructor(props) {
        super(props);
        this.state = {
          count: 0,
        };
        this.cryptoPicCaptcha = debounce(this.cryptoPicCaptcha, 300, {
          leading: false,
          trailing: true,
        });
      }

      componentDidMount() {
        const { updateActive } = this.context;
        const { name } = this.props;
        if (updateActive) {
          updateActive(name);
        }
        this.cryptoPicCaptcha();
      }

      componentWillUnmount() {
        clearInterval(this.interval);
      }

      componentDidUpdate(preProps) {
        const { captchaUrl, action } = preProps;
        const { captchaUrl: nextCaptchaUrl, action: nextAction } = this.props;
        if (!nextCaptchaUrl || !nextAction) return;
        if (nextCaptchaUrl !== captchaUrl || nextAction !== action) {
          this.cryptoPicCaptcha();
        }
      }

      onGetCaptcha = () => {
        let count = 59;
        this.setState({ count });
        const { onGetCaptcha } = this.props;
        if (onGetCaptcha) {
          onGetCaptcha();
        }
        this.interval = setInterval(() => {
          count -= 1;
          this.setState({ count });
          if (count === 0) {
            clearInterval(this.interval);
          }
        }, 1000);
      };

      cryptoPicCaptcha = () => {
        const { action, captchaUrl } = this.props;
        if (!action) return;
        const { phone } = qs.parse(captchaUrl, { ignoreQueryPrefix: true });
        if (check('phone', phone).code > 0) return;
        this.setState({
          imgloading: true,
        });
        crypto({ url: action }).then(url => {
          this.setState({
            captchaUrlWithCrypto: url + captchaUrl.replace('?', '&'),
          });
        });
      };

      onGetPicCaptcha = () => {
        this.cryptoPicCaptcha();
      };

      onPicCaptchaLoaded = () => {
        this.setState({
          imgloading: false,
        });
      };

      render() {
        const { form } = this.context;
        const { getFieldDecorator } = form;
        const options = {
          validateTrigger: 'onBlur',
        };
        let otherProps = {};
        const { onChange, defaultValue, buttonText, rules, name, ...restProps } = this.props;
        const { count, imgloading = true, captchaUrlWithCrypto } = this.state;
        options.rules = rules || defaultRules;
        if (onChange) {
          options.onChange = onChange;
        }
        if (defaultValue) {
          options.initialValue = defaultValue;
        }
        otherProps = restProps || otherProps;
        if (type === 'Captcha') {
          const inputProps = omit(otherProps, ['onGetCaptcha']);
          return (
            <FormItem>
              <Row gutter={8}>
                <Col span={16}>
                  {getFieldDecorator(name, options)(
                    <WrappedComponent {...defaultProps} {...inputProps} />,
                  )}
                </Col>
                <Col span={8}>
                  <Button
                    disabled={count}
                    className={styles.getCaptcha}
                    size="large"
                    onClick={this.onGetCaptcha}
                  >
                    {count ? `${count} s` : buttonText}
                  </Button>
                </Col>
              </Row>
            </FormItem>
          );
        } else if (type === 'PicCaptcha') {
          const inputProps = omit(otherProps, ['onGetPicCaptcha']);
          return (
            <FormItem>
              <Row gutter={8}>
                <Col span={16}>
                  {getFieldDecorator(name, options)(
                    <WrappedComponent {...defaultProps} autoComplete="off" {...inputProps} />,
                  )}
                </Col>
                <Col span={8} className={styles['pic-captcha']}>
                  <Spin spinning={imgloading}>
                    <Tooltip title="看不清？点击刷新">
                      <div className={styles['pic-captcha-div']}>
                        {captchaUrlWithCrypto && (
                          <img
                            alt=""
                            onLoad={this.onPicCaptchaLoaded}
                            onClick={this.onGetPicCaptcha}
                            src={captchaUrlWithCrypto}
                          />
                        )}
                      </div>
                    </Tooltip>
                  </Spin>
                </Col>
              </Row>
            </FormItem>
          );
        }
        return (
          <FormItem>
            {getFieldDecorator(name, options)(
              <WrappedComponent {...defaultProps} {...otherProps} />,
            )}
          </FormItem>
        );
      }
    };
  };
}

const LoginItem = {};
Object.keys(map).forEach(item => {
  LoginItem[item] = generator({
    defaultProps: map[item].props,
    defaultRules: map[item].rules,
    type: item,
  })(map[item].component);
});

export default LoginItem;

/* eslint-enable */
